package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.LocalDate;
import org.joda.time.Weeks;

import com.easyattendance.model.Student;
import com.easyattendance.services.AddHolidayListService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.AttendanceService;

/**
 * Servlet implementation class GetSectionReportsServlet
 */
@WebServlet("/GetSectionReportsServlet")
public class GetSectionReportsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
        
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    	response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String actionType = request.getParameter("action_type");
		
		if(actionType.equals("syllabus")) {
			AddSubjectService addSubjectService = new AddSubjectService();
			AddTeacherService addTeacherService = new AddTeacherService();
			AddSectionService addSectionService = new AddSectionService();
			AddHolidayListService holidayService = new AddHolidayListService();
			boolean dispatcherFlag = false;
			
			String sectionId = request.getParameter("section_id");
			String classId = request.getParameter("class_selected");
			String teacherId = request.getParameter("teacher_selected");
			String subjectId = request.getParameter("syll_select_subject");
			int lectureStatus=0;
			
			if(teacherId!= null && subjectId!= null){
			    lectureStatus = addSubjectService.getSubjectTeacherStatusByIds(teacherId, subjectId);
				long teacherSubjectLectureStatus = 0;
				
				if(lectureStatus != 1000) {
					
					Date termStart = addSectionService.getSectionBySectionId(sectionId).getTerm_start_date();
					Date termEnd = addSectionService.getSectionBySectionId(sectionId).getTerm_end_date();
					 
					
					LocalDate start = new LocalDate(termStart);
					System.out.println("Yoda::: "+ start);
					LocalDate end = new LocalDate(termEnd);
					
					java.sql.Timestamp sql1 = new java.sql.Timestamp(start.getYear(), start.getMonthOfYear(), start.getDayOfMonth(), 0, 0,0,0);
			        java.sql.Timestamp sql2 = new java.sql.Timestamp(end.getYear(), end.getMonthOfYear(), end.getDayOfMonth(), 0, 0,0,0);
					
					//int totalWorkingDays = holidayService.getWorkingDaysExcludingWeekends(start, end);
					
					//LocalDate termDays = new LocalDate(sql2.getTime() - sql1.getTime());
					
					// calculate total weeks between term start and sysdate and then multiple it with total subj lectures of a teacher in 1 week
					int totalWeeksInTerm = Weeks.weeksBetween(start, new LocalDate()).getWeeks();
					int totalWorkingDays = totalWeeksInTerm * (addSubjectService.getSubTeacherByIds(subjectId, teacherId).getTotal_lecture_status());
					
					int totalHolidays = holidayService.getTotalHolidaysBetweenDates(sectionId, sql1, sql2);
					
					
					System.out.println("working days: "+ totalWorkingDays+" holidays:::"+ totalHolidays);
					
					teacherSubjectLectureStatus = ((lectureStatus* 100)/(totalWorkingDays - totalHolidays));
					out.println("Lecture status of this teacher is: "+lectureStatus);
				}
				else {
					//out.println("No data found");
					request.setAttribute("no_data_found", "No Teacher-Subject lecture records found");
		        	dispatcherFlag = true;
				}
			}
			else {
				//out.println("Data selected cannot be blank.. Choose again");
				request.setAttribute("null_values", "Values cannot be null");
	        	dispatcherFlag = true;
			}
			
			if(!dispatcherFlag) {
			    request.setAttribute("lectureStatus","Lecture status of "+addTeacherService.getTeacherById(teacherId).getTeacher_name()+" "+addTeacherService.getTeacherById(teacherId).getTeacher_lname()+" for "+addSubjectService.getSubjectBySubjectId(subjectId).getSubject_name()+
			    		" subject in Class "+classId+" = "+lectureStatus);
				RequestDispatcher rd = request.getRequestDispatcher("views/section/reports.jsp");
		    	rd.forward(request, response);
			}
			
			/*RequestDispatcher rd = request.getRequestDispatcher("views/admin/displayTeacherLectureStatusReport.jsp");
	    	rd.forward(request, response);*/
		}
		else if(actionType.equals("attendance")) {
			String sectionId = request.getParameter("section_id");
			String classId = request.getParameter("att_select_class");
			boolean dispatcherFlag = false;
		
			
			Date date1=null,date2=null;
			java.sql.Date startDate=null,endDate=null;
			
			 try {
				date1 = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("from"));
				date2 = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("to"));
				
				 startDate=new java.sql.Date(date1.getTime());
				 endDate=new java.sql.Date(date2.getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
	        java.sql.Timestamp sql1 = new java.sql.Timestamp(startDate.getTime());
	        java.sql.Timestamp sql2 = new java.sql.Timestamp(endDate.getTime());
			System.out.println("from: "+startDate+" to: "+endDate+" sql:"+sql1+ ": "+ sql2);
			
			AttendanceService attendanceService = new AttendanceService();
			AddSectionService addSectionService = new AddSectionService();
			AddHolidayListService holidayService = new AddHolidayListService();
			
			Date termStart = addSectionService.getSectionBySectionId(sectionId).getTerm_start_date();
			Date termEnd = addSectionService.getSectionBySectionId(sectionId).getTerm_end_date();
			 
			
			LocalDate start = new LocalDate(termStart);
			System.out.println("Yoda::: "+ start);
			LocalDate end = new LocalDate(termEnd);
			
			int totalWorkingDays = holidayService.getWorkingDaysExcludingWeekends(start, end);
			int totalHolidays = holidayService.getTotalHolidaysBetweenDates(sectionId, sql1, sql2);
			//int totalWorkingDays = Days.daysBetween(end, start).getDays();
					//(int)( (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
			
			System.out.println("working days: "+ totalWorkingDays+" holidays:::"+ totalHolidays);
			
			ArrayList<Student> studentList = attendanceService.getStudentList(classId);
			 
			int[] studentPresentDays = attendanceService.getStudentPresentDays(classId, sql1, sql2);
			long[] studentAttendance = new long[studentPresentDays.length];
			
			if(studentList.isEmpty()) {
				request.getSession().setAttribute("students_not_found", "No Student Record Found");
	        	dispatcherFlag = true;
			}
			
			if(studentPresentDays.length == 0) {
				request.getSession().setAttribute("no_attendance_record", "No Student Attendance Records Found");
	        	dispatcherFlag = true;
			}
			
			for(int i=0; i<studentPresentDays.length; i++) {
				System.out.println("present days "+studentPresentDays[i]);
				System.out.println("present days % of stud "+i+" "+ (studentPresentDays[i]* 100)/(totalWorkingDays - totalHolidays));
				studentAttendance[i] = ((studentPresentDays[i]* 100)/(totalWorkingDays - totalHolidays));
			}
			
			request.getSession().setAttribute("student_list", studentList);
			request.getSession().setAttribute("student_attendance", studentAttendance);
			request.getSession().setAttribute("start_date", startDate);
			request.getSession().setAttribute("end_date", endDate);
			
			if(dispatcherFlag) {
				/*RequestDispatcher rd = request.getRequestDispatcher("views/admin/reports.jsp");
		    	rd.forward(request, response);*/
				response.sendRedirect("views/section/reports.jsp");
			}
			else
			{
				/*RequestDispatcher rd = request.getRequestDispatcher("views/admin/displayReports.jsp");
		    	rd.forward(request, response); */
				response.sendRedirect("views/section/displayReports.jsp");
			}
		}
		else {
			boolean dispatcherFlag = false;
			
			String sectionId = request.getParameter("section_id");
			String classId = request.getParameter("class_selected");
			String subjectId = request.getParameter("sub_syll_select_subject");
			
			AddSubjectService addSubjectService = new AddSubjectService();
			AddSectionService addSectionService = new AddSectionService();
			
			if(sectionId != null && classId !=null && subjectId != null) {
				int subjectLectureStatus = addSubjectService.getSubjectStatusById(subjectId, classId);
				int subjectStatus = 0;
				
				if(subjectLectureStatus != 1000) {
					Date termStart = addSectionService.getSectionBySectionId(sectionId).getTerm_start_date();
					Date termEnd = addSectionService.getSectionBySectionId(sectionId).getTerm_end_date();
					
					LocalDate start = new LocalDate(termStart);
					
					// calculate total weeks between term start and sysdate and then multiple it with total lectures of a subject in 1 week
					int totalWeeksInTerm = Weeks.weeksBetween(start, new LocalDate()).getWeeks();
					int totalWorkingDays = totalWeeksInTerm * (addSubjectService.getSubjectClassByIds(subjectId, classId).getTotal_lecture_hours());
					
					System.out.println("working days: "+ totalWorkingDays);
					
					if(totalWorkingDays != 0 ){
						subjectStatus = ((subjectLectureStatus* 100)/(totalWorkingDays));
						//out.println("Lecture status of this subject is: "+subjectStatus);
						
						request.setAttribute("subjectLectureStatus","Lecture status of subject: "+addSubjectService.getSubjectBySubjectId(subjectId).getSubject_name()+" in Class: "+classId+" is "+subjectStatus); 
						RequestDispatcher rd = request.getRequestDispatcher("views/section/reports.jsp");
				    	rd.forward(request, response);
					}
					else {
						request.setAttribute("no_data_found", "No Subject lecture records found");
			        	dispatcherFlag = true;
					}
					
				}
				else {
					//out.println("No data found");
					request.setAttribute("no_data_found", "No Subject lecture records found");
		        	dispatcherFlag = true;
				}
			}
			else {
				request.setAttribute("null_values", "Values cannot be null");
	        	dispatcherFlag = true;
			}
		}
		
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);	
	}

}

